package com.foxconn.ipebg.common.system.controller;

import ipebg.mzk.common.util.JavaMD5;
import ipebg.mzk.common.util.Page;
import ipebg.mzk.facade.entity.MsAdminUser;
import ipebg.mzk.facade.entity.Org;
import ipebg.mzk.facade.system.bean.AdminUserBean;
import ipebg.mzk.facade.system.service.MenuService;
import ipebg.mzk.facade.system.service.OrgService;
import ipebg.mzk.facade.system.service.UserRoleService;
import ipebg.mzk.facade.system.service.UserService;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;


/**
 * 對菜單項操作方法
 * @author F3225975
 *
 *
 */
@Controller
@RequestMapping("/user.do")
public class UserController {
	private static Log log = LogFactory.getLog(UserController.class);
	@Resource(name="userServiceImpl")
	UserService userService;
	
	
	
	 
	@Resource(name="userRoleServiceImpl")
	UserRoleService userRoleService;
	
	@Resource(name="orgServiceImpl")
	OrgService orgService;
	
	/**
	 * 加載個人中心頁面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "action=userCenter")
	public String userCenter(HttpServletRequest request, HttpServletResponse response, Model model) {
		String loginName = SecurityContextHolder.getContext().getAuthentication().getName();
		MsAdminUser user = userService.findUserByEmpNo(loginName);
		String orgName = "";
		if(user.getOrgId()!=null&&!user.getOrgId().equals("")){
			Org org = orgService.findById(user.getOrgId());
			if (org != null) {
				orgName = org.getOrgName()+"-"+org.getOrgFee();
			}
		}
		model.addAttribute("currentUser", user);
		model.addAttribute("orgName", orgName);
		return "/pages/common/system/user_center";
	}
	
	/**
	 * 修改個人信息方法
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=editUser")
	public void editUser (HttpServletRequest request, HttpServletResponse response, Model model) {
		String loginName = request.getParameter("loginName");
		String phone = request.getParameter("phone");
		String telePhone = request.getParameter("telePhone");
		String email = request.getParameter("email");
		String description = request.getParameter("description");
		
		MsAdminUser user = userService.findUserByEmpNo(loginName);
		user.setPhone(phone);
		user.setTelePhone(telePhone);
		user.setEmail(email);
		user.setDescription(description);
		user.setEditTime(new Date());
		
		userService.saveOrUpdate(user);

		Org org = orgService.findById(user.getOrgId());
		String orgName = org.getOrgName()+"-"+org.getOrgFee();
		model.addAttribute("user", user);
		model.addAttribute("orgName", orgName);
		
		try {
			response.getWriter().write("success");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 個人修改密碼功能
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=modifyPwd")
	public void modifyPwd(HttpServletRequest request, HttpServletResponse response, Model model) {
		String result = "";
		
		String userId = request.getParameter("userId");
		String oldPwd = request.getParameter("oldpassword");
		String password = request.getParameter("password");
		
		MsAdminUser user = userService.findUserById(userId);
		JavaMD5 md5 = new JavaMD5();
		oldPwd = md5.getMD5ofStr(oldPwd).toLowerCase();
		
		if(user.getPassword() == oldPwd || user.getPassword().equals(oldPwd)){
			user.setPassword(md5.getMD5ofStr(password).toLowerCase());
			userService.saveOrUpdate(user);
			result = "success";
		}else{
			result = "pwderror";
		}
		
		try {
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	 
	/**
	 * 加載用戶列表頁面方法
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "action=load")
	public String load(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/pages/common/system/user_manage";
	}
				
	/**
	 * 用戶列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(params = "action=list")
	public void functionList(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		int from = Integer.parseInt(request.getParameter("page"));
		int length = Integer.parseInt(request.getParameter("rows")); 
		
		String loginName = request.getParameter("loginName");
		String realName = request.getParameter("realName");
		MsAdminUser user = new MsAdminUser();
		user.setLoginName(loginName);
		user.setRealName(realName);
		
		try {
			Page initiontpage = userService.getAllList(user,from,length);
			List<MsAdminUser> userList= (List<MsAdminUser>) initiontpage.getResult();
			List<AdminUserBean> userBeanList = userService.toBean(userList);
								
			Map objMap = new HashMap();
			objMap.put("rows", userBeanList);
			objMap.put("total", initiontpage.getTotalCount());
			
			response.getWriter().write(JSON.toJSONString(objMap));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 新增用戶功能
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=add")
	public void add(HttpServletRequest request, HttpServletResponse response, Model model) {
		String result = "";
		
		String loginName = request.getParameter("loginName");
		String realName = request.getParameter("realName");
		String password = request.getParameter("password");
		String phone = request.getParameter("phone");
		String telePhone = request.getParameter("telePhone");
		String orgId = request.getParameter("orgId");
		String dominate = request.getParameter("dominate");
		String email = request.getParameter("email");
		String description = request.getParameter("description");
		MsAdminUser user = userService.findUserByEmpNo(loginName);
		if(user != null && !user.getEnabled().equals("2")){
			result = "exsit";
		}else{
			if(user == null)
				user = new MsAdminUser();
			user.setLoginName(loginName);
			user.setRealName(realName);
			JavaMD5 md5 = new JavaMD5();
			user.setPassword(md5.getMD5ofStr(password).toLowerCase());
			user.setPhone(phone);
			user.setTelePhone(telePhone);
			user.setOrgId(orgId);
			user.setDominate(dominate);
			user.setEmail(email);
			user.setDescription(description);
			user.setEnabled("1");
			user.setCreatedTime(new Date());
			user.setEditTime(new Date());
			userService.saveOrUpdate(user);
			result = "success";
		}
		try {
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 編輯用戶功能
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=edit")
	public void edit(HttpServletRequest request, HttpServletResponse response, Model model) {
		String result = "";
		
		String userId = request.getParameter("userId");
		String loginName = request.getParameter("loginName");
		String realName = request.getParameter("realName");
		String phone = request.getParameter("phone");
		String telePhone = request.getParameter("telePhone");
		String orgId = request.getParameter("orgId");
		String dominate = request.getParameter("dominate");
		String email = request.getParameter("email");
		String description = request.getParameter("description");
		
		MsAdminUser user = userService.findUserById(userId);
		MsAdminUser validateUser = userService.findUserByEmpNo(loginName);
		
		if(loginName != null & !(validateUser.getAdminId() == userId || validateUser.getAdminId().equals(userId))){
			result = "exsit";
		}else{
			user.setLoginName(loginName);
			user.setRealName(realName);
			user.setPhone(phone);
			user.setTelePhone(telePhone);
			user.setOrgId(orgId);
			user.setDominate(dominate);
			user.setEmail(email);
			user.setDescription(description);
			user.setEnabled("1");
			user.setEditTime(new Date());
			
			userService.saveOrUpdate(user);
			
			result = "success";
		}
		try {
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 刪除用戶功能
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=delete")
	public void delete(HttpServletRequest request, HttpServletResponse response, Model model) {
		String userId = request.getParameter("userId");
		try {
			//需要判斷是否在UserRole表中使用
			if(userRoleService.getUserRoleListByUserId(userId).size()>0){
				//說明用戶已分配角色，不能刪除
				response.getWriter().write("exsit");
			}else{
				if(userService.delete(userId)){
					response.getWriter().write("success");
				}else{
					response.getWriter().write("error");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 啟用or禁用用戶功能
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=enable")
	public void enable(HttpServletRequest request, HttpServletResponse response, Model model) {
		String result = "";
		
		String userId = request.getParameter("userId");
		String enable = request.getParameter("enable");
		
		MsAdminUser user = userService.findUserById(userId);
		user.setEnabled(enable);
		
		userService.saveOrUpdate(user);
			
		result = "success";
		try {
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 重置密碼功能
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=reset")
	public void reset(HttpServletRequest request, HttpServletResponse response, Model model) {
		String result = "";
		
		String userId = request.getParameter("userId");
		String password = request.getParameter("password");
		
		MsAdminUser user = userService.findUserById(userId);
		JavaMD5 md5 = new JavaMD5();
		user.setPassword(md5.getMD5ofStr(password).toLowerCase());
		
		userService.saveOrUpdate(user);
			
		result = "success";
		try {
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
